const fs = require('fs');
const path = require('path');
const writeToPath = path.resolve(__dirname, '../imgs/index.js');
const readFromDir = path.resolve(__dirname, '../imgs/default');
const domain = 'https://app-miaoshoucdn-com.oss-cn-shanghai.aliyuncs.com/chengdu/doctor-miniapp/';

// 文件处理
const dealFiles = async (path, sourceFiles) => {
  if (!sourceFiles.length) return [];
  let targetFiles = [];
  let fileName = '';
  for (let i = 0; i < sourceFiles.length; i++) {
    fileName = sourceFiles[i];
    if (/^[\w-]*(\.jpeg|\.png|\.jpg|\.svg)$/.test(fileName)) {
      targetFiles.push({
        path: path.replace(/^\//, ''),
        fileName: fileName,
      });
    } else if (/^[^.]/.test(fileName)) { // 非以点开头文件,过滤掉系统生成隐藏文件
      const results = await readFiles(`${path}/${fileName}`);
      if (results.length) {
        targetFiles = [...targetFiles, ...results];
      }
    }
  }
  return targetFiles;
}

// 文件读取
const readFiles = (path) => {
  return new Promise((resolve) => {
    fs.readdir(`${readFromDir}${path}`, (err, files) => {
      if (err) {
        console.log(path, '====>', err);
        resolve([]);
      } else {
        dealFiles(path, files).then((results) => {
          resolve(results);
        }).catch(() => {
          resolve([]);
        });
      }
    });
  });
}

const writeIndexFile = (files) => {
  let imgTsContent = `const domain = '${domain}';\n`;
  files.forEach(file => {
    const statementName = file.fileName.replace(/([^.]+)\..+/, '$1').replace(/[-_]([a-z])/g, (val, $1) => $1.toUpperCase());
    imgTsContent += `export const ${statementName}Img = domain + '${file.path}${file.path ? '/' : ''}${file.fileName}';\n`;
  });
  fs.writeFileSync(writeToPath, imgTsContent);
}

readFiles('').then((files) => {
  console.log('readFromDir length===>', files?.length);
  writeIndexFile(files);
});
